var e = require("/yb_mingpian/utils/core.js");
import regeneratorRuntime from '/regenerator-runtime/runtime.js';
App({
  core: require("./yb_mingpian/utils/core.js"),
  
    async onLaunch(e) {

      console.log("onLaunch123: ",e)

    var pid=0;
    var that = this;
    if (e.query.pid){
      pid=e.query.pid
    }
    that.setCache('pid',pid);
    var res = await this.getExtC();
    this.set_caidan(function (t) {
    });
    this.getOpenId();
  },

  //version:'1.0.81',
  version:'19.09.25',

      getExtC: function () {
        var that = this;
        return new Promise(function (resolve, reject){
            if (wx.getExtConfig) {
                wx.getExtConfig({
                    success: function (res) {
                        console.log(res,'获取的第三方平台的信息')
                        if (res.errMsg == "getExtConfig: ok") {
                            console.log("getExtConfig: ok")
                            if (res.extConfig.siteroot) {
                                console.log("siteInfo: " + res.extConfig.siteroot);
                                console.log("uniacid: " + res.extConfig.uniacid);
                                that.globalData.appid = res.extConfig.app_key ? res.extConfig.app_key : '';
                                that.globalData.app_name = res.extConfig.app_name ? res.extConfig.app_name : getApp().globalData.app_name;
                                getApp().siteInfo.siteroot = res.extConfig.siteroot ? res.extConfig.siteroot : '';
                                getApp().siteInfo.uniacid = res.extConfig.uniacid ? res.extConfig.uniacid : '';
                            }
                            console.log(getApp().siteInfo);
                        }
                        getApp().siteInfo.loaded = true;
                        resolve(1);
                    }
                })
            }
            else {
                getApp().siteInfo.loaded = true;
                resolve(1);
            }

        });

    },

  //用户操作记录
  userlog: function (op_type, op_name, push_type, de_id = 0) {
    var that = this;
    var userInfo = that.getCache('userinfo');
    if (userInfo.nickName && userInfo.avatarUrl){
      e.get('Card/behavior', {
        staff_id: that.globalData.card_id,
        user_id: that.getCache('userinfo').uid,
        op_type: op_type,
        push_type: push_type,
        op_name: op_name,
        de_id:de_id
      }, function (t) {
        //console.log(t)
      });
    }
    
  },
  //未读消息数量+ 是否获取手机号
  get_news_num: function (that) {
    var _that = this;
    if (_that.getCache('userinfo').uid == undefined || _that.getCache('userinfo').uid == '') {
        return;
    }
    e.get('Card/wdnews', {
      user_id: _that.getCache('userinfo').uid,
      staff_id: _that.globalData.card_id
    }, function (t) {
      if (t.code == 0) {
        that.setData({
          news_num: t.info
        })
      }
    })
    var arr = {};
    arr['staff_id'] = _that.globalData.card_id;
    arr['user_id'] = _that.getCache("userinfo").uid;
    e.get('Card/getPhone', arr, function (t) {
      //console.log(t)
      if (t.code == 0) {
        that.setData({
          get_phone: false
        })
      }else{
        that.setData({
          get_phone: true
        })
      }
        that.setData({
          phone_status: t.info
        })
        // that.setData({
        //   company_status: t.company_status
        // })
      console.log("pho",t);
      // console.log("pho",company_status);
    })
  },
  //分销发展下线
  set_share_pid: function (pid) {
    var uid = this.getCache("userinfo").uid;
    if (uid && pid && pid != 0 && pid!=uid) {
      e.get('Distribe/addman', {
        uid: uid,
        pid: pid
      }, function (t) {
        //console.log(t)
      })
    }
  },
 
  //授权手机号,type:1,跳转聊天；2,保存通讯录,3,不做处理
  getPhoneNumber: function (n, that, type_) {
  var t=this;
    wx.checkSession({
      success: function () {
        //console.log(111111)
        //session_key 未过期，并且在本生命周期一直有效
      },
      fail: function () {
        console.log('getPhoneNumber:fail');
        // session_key 已经失效，需要重新执行登录流程
        t.get_sessionKey();
      }
    })
    if (!t.getCache("sessionKey")) {
      t.get_sessionKey();
    }
    var arr = {};
    arr['staff_id'] = t.globalData.card_id;
    arr['user_id'] = t.getCache("userinfo").uid;
    e.get('Card/getPhone', arr, function (k1) {
      //console.log(k1)
      if (k1.code == 0) {
        if (type_== 1) {
          that.to_chat();
        }
        if (type_== 2) {
          that.addPhoneContact();
        }
      } else {
        if (n.detail.errMsg == 'getPhoneNumber:ok') {
          arr['sessionKey'] = t.getCache("sessionKey");
          arr['iv'] = n.detail.iv;
          arr['encryptedData'] = n.detail.encryptedData;
          e.post('Card/savePhone', arr, function (k2) {
            //if(k2.code!=0){
             // t.get_sessionKey();
           // }
            if (type_== 1) {
              that.to_chat();
            }
            if (type_== 2) {
              that.addPhoneContact();
            }
          })
        } else {
          if (type_== 1) {
            that.to_chat();
          }
          if (type_== 2) {
            that.addPhoneContact();
          }
        }
      }
    })
  },
  set_caidan: function (obj) {
    // wx.hideTabBar()
    var that = this;
    wx.request({
      url: that.siteInfo.siteroot + '?i=' + that.siteInfo.uniacid + '&t=undefined&from=wxapp&c=entry&a=wxapp&do=index_tabbar&m=yb_mingpian&sign=1d917db727d0aa4e23ca117826fa3153' + '&v=' + that.version, //仅为示例，并非真实的接口地址
      data: {},
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (t) {
        if (t.errMsg == "request:ok") {
          if (typeof (t.data) == "string") {
            if (t.data.indexOf("html") >= 0 && t.data.indexOf("head") >= 0 && t.data.indexOf("body") >= 0) {
              e.error('请求错误004！');
              return;
            }
          }
          if (t.data == '') {
            //console.log('请求异常005！');
            //e.error('请求异常！');
            return;
          }
          //转json对象
          if (typeof t.data == 'string') {
            t.data = e.json_parse(t.data);
          }
          console.log("tabbar",t);
          if (t.data.code == 0) {
            if (t.data.info && t.data.info.page){
                console.log("page_config",t.data.info.page);
            that.config.nv_color = t.data.info.page.nv_color;
            that.config.button_color = t.data.info.page.button_color;
            that.config.alert_color = t.data.info.page.button_color;
            that.config.bg_color = t.data.info.page.bg_color;
            that.config.text_color = t.data.info.page.text_color;
            that.config.background = t.data.info.tabbar.button_color;
            that.config.selectedColor = t.data.info.tabbar.select_color;
            that.config.font_color = t.data.info.page.text_color == '#ffffff' ? 'white' :'black';
            if (t.data.info.page.show_tabbar && t.data.info.page.show_tabbar == 'false'){
              wx.hideTabBar();
            }else{
              wx.showTabBar();
            }
          }

          } 
          "function" == typeof obj && obj(1000);
        }
      }
    })
  },
  // config: {//测试用
  //   bg_color: '#80ff00',
  //   nv_color: '#000040',
  //   text_color: '#ffffff',
  //   background: '#ffffff',//首页搜索、个人汇中心背景#000cf.color.background
  //   button_color: '#000040',//商品详情按钮，提交订单、确认支付按钮，购物车结算按钮
  //   alert_color: '#000040',//信息提示，表单提交按钮oI9vSwl9OO4Vggsuy65nL_qZYprY
  //   font_color: 'black',
  //   selectedColor: "#0eb799"
  // },
  config: {
    bg_color: '#F4F4F4',
    nv_color: '#ffffff',
    text_color:'#000000',
    background: '#ffffff',//首页搜索、个人汇中心背景#000cf.color.background
    button_color: '#0eb799',//商品详情按钮，提交订单、确认支付按钮，购物车结算按钮
    alert_color: '#0eb799',//信息提示，表单提交按钮oI9vSwl9OO4Vggsuy65nL_qZYprY
    font_color: 'black',
    selectedColor: "#df2f20"
  },
  requirejs: function (e) {
    return require("yb_mingpian/utils/" + e + ".js")
  },

    // 授权开关
    authSwitch: function (fun) {
        var n = this;
        e.get("user/authSwitch", {

        }, function (res) {
            fun && "function" == typeof fun && fun(res.info);
        })
    },

  // 登录获取用户openid
  getOpenId: function (t) {
    var n = this,
        openid = '',
        sessionKey = '',
        a = n.getCache("userinfo");
    n.globalData.getphone = false;
    if (a) return void (t && "function" == typeof t && t(a));

    wx.login({
      success: function (o) {
        if (!o.code) return void e.alert("获取用户登录态失败2");

        e.get("user/openid", {
          wx_code: o.code
        }, function (o) {
          if (o.code == 0) {

            if (!o.info.errcode) {
              openid = o.info.openid;
              sessionKey = o.info.session_key;
              n.setCache('sessionKey', o.info.session_key);

              var u_info = {};
              u_info.openid = openid;
              u_info.uid = o.info.uid;
              u_info.nickName = o.info.nickName;
              u_info.avatarUrl = o.info.avatarUrl;
              n.setCache("userinfo", u_info);

              // 记录访问信息
              // if (n.globalData.card_id > 0) {
              //   e.get("Card/GoodsCardList", {
              //     uid: o.info.uid,
              //     staff_id: n.globalData.card_id,
              //     source: n.globalData.user_source
              //   }, function (res) {
              //     console.log("visit1", res);
              //   })
              // }
              "function" == typeof t && t(u_info);
            } else {
              e.alert('errcode:' + o.info.errcode + ';errmsg:' + o.info.errmsg);
              "function" == typeof t && t(1000);
              return false;
            }
          } else {
            e.alert(o.msg);
            "function" == typeof t && t(1000);
            return false;
          }
        })
      }
    })
  },

  getUserInfo: function (userInfo, t, encryptedData = null, iv = null) {
    console.log("userinfo55555",userInfo);
    var n = this,
        openid = '',
        sessionKey = '',
        a = n.getCache("userinfo");
    n.globalData.getphone = false;
    if (a.nickName && a.avatarUrl) return void (t && "function" == typeof t && t(a));

    wx.login({
      success: function (o) {
        if (!o.code) return void e.alert("获取用户登录态失败2");
        //console.log(o)
        e.get("user/openid", {
          wx_code: o.code
        }, function (o) {
          if (o.code == 0) {

            if (!o.info.errcode) {
              openid = o.info.openid;
              sessionKey = o.info.session_key;
              n.setCache('sessionKey', o.info.session_key);

              var u_info = {};
              u_info.openid = openid;
              u_info.uid = o.info.uid;
              u_info.nickName = o.info.nickName;
              u_info.avatarUrl = o.info.avatarUrl;
              n.setCache("userinfo", u_info);

            } else {
              e.alert('errcode:' + o.info.errcode + ';errmsg:' + o.info.errmsg);
              return false;
            }
          } else {
            e.alert(o.msg);
            "function" == typeof t && t(1000);
            return false;
          }

          // 查看用户是否授权
          wx.getSetting({
            success(res) {
              if (res.authSetting['scope.userInfo']) {
                e.get("user/Login", {
                  wx_openid: openid,
                  nick_name: userInfo.nickName,
                  user_headimg: userInfo.avatarUrl,
                  gender: userInfo.gender,
                  pid:n.getCache('pid'),
                  staff_id: n.globalData.card_id,
                  encryptedData: encryptedData,
                  iv: iv,
                  sessionKey: n.getCache('sessionKey')
                }, function (ve) {
                  console.log("abd", ve);
                  // 获取用户手机号是否授权
                  if (!ve.pinfo.phone && ve.pinfo.status.login_get_pho == 1) {
                    n.globalData.getphone = true;
                  }

                  var uid = ve.info != null ? ve.info : '0';
                  var formid = n.getCache('login_formid');

                  if (formid) {
                    e.get('Market/getFormid', {
                      formid: formid,
                      openid: openid,
                      username: userInfo.nickName
                    }, function (t) {
                      n.removeCache('login_formid');
                      //console.log('授权登录获取表单id')
                    })
                  }

                  // 记录访问信息
                  if (n.globalData.card_id > 0) {
                    e.get("Card/GoodsCardList", {
                      uid: uid,
                      staff_id: n.globalData.card_id,
                      source: n.globalData.user_source
                    }, function (res) {
                      console.log("visit2", res);
                    })
                  }

                  //this.globalData.uid=e.info
                  userInfo.openid = openid, userInfo.uid = uid, n.setCache("userinfo", userInfo), t && "function" == typeof t && t(a)
                })
              } else {
                // 拒绝授权
                //e.alert("授权失败，请重试");
                t && "function" == typeof t && t(a)
                //getCurrentPages()[getCurrentPages().length - 1].onLoad();
              }
            }
          })

        })
      },
      fail: function () {
        "function" == typeof t && t(1000)
        e.alert("获取用户信息失败")
      }
    })
  },
  get_sessionKey:function(){
    var that=this;
    wx.login({
      success: function (o) {
        if (!o.code) return void e.alert("获取用户登录态失败2");
        //console.log(o)
        e.get("user/openid", {
          wx_code: o.code
        }, function (o) {
          //console.log(o)
          if (o.code == 0) {
            if (!o.info.errcode) {
              that.setCache('sessionKey', o.info.session_key);
            } else {
              e.alert(o.info.errmsg);
              return false;
            }
          } else {
            e.alert(o.msg);
            "function" == typeof t && t(1000);
            return false;
          }
        })
      }
    })
  },
  onLoad: function (options) {
    wx.cloud.init({
      traceUser: true,
      })
  },
  isInArray: function (arr, value) {
    for (var i = 0; i < arr.length; i++) {
      if (value == arr[i].key) {
        var str=arr[i].imgurl;
        return str.charAt(str.length - 1);
      }
    }
    return false;
  },
  tabBar: {
    name: "超级名片",
    background: "#F4F4F4",
    backgroundTextStyle: "#000000",
    backgroundColor: "#FFF5EE",
    color: "#8b8b8b",
    selectedColor: "#0eb799",
    list: [
      {
        pagePath: "yb_mingpian/pages/cardinfo/index",
        text: "名片",
        iconPath: "yb_mingpian/static/card/icon/white_0.png",
        selectedIconPath: "yb_mingpian/static/card/icon/green_0.png"
      },
      {
        pagePath: "yb_mingpian/pages/shop/index",
        text: "商城",
        iconPath: "yb_mingpian/static/card/icon/white_1.png",
        selectedIconPath: "yb_mingpian/static/card/icon/green_1.png"
      },
      {
        pagePath: "yb_mingpian/pages/message/index",
        text: "动态",
        iconPath: "yb_mingpian/static/card/icon/white_2.png",
        selectedIconPath: "yb_mingpian/static/card/icon/green_2.png"
      },
      {
        pagePath: "yb_mingpian/pages/index/index",
        text: "官网",
        iconPath: "yb_mingpian/static/card/icon/white_3.png",
        selectedIconPath: "yb_mingpian/static/card/icon/green_3.png"
      }
    ]
  },
  /*
   * 获取缓存
   * @param e 缓存名称
   * @param t 缓存值
   */
  getCache: function (e, t) {
    var i = +new Date / 1000,
    that=this,
      n = "";
    i = parseInt(i);
    try {
      n = wx.getStorageSync(e + that.globalData.appid), n.expire > i || 0 == n.expire ? n = n.value : (n = "", that.removeCache(e))
    } catch (e) {
      n = void 0 === t ? "" : t
    }
    return n = n || ""
  },
  /*
   * 创建缓存
   * @param e 缓存名称
   * @param t 缓存值
   * @param i 缓存时间
   */
  setCache: function (e, t, i) {
    var n = +new Date / 1000,
      a = true,
      o = {
        expire: i ? n + parseInt(i) : 0,
        value: t
      };
    try {
      wx.setStorageSync(e + this.globalData.appid, o)
    } catch (e) {
      a = false
    }
    return a
  },
  /*
   * 清除缓存
   * @param e 缓存名称
   */
  removeCache: function (e) {
    var t = true;
    try {
      wx.removeStorageSync(e + this.globalData.appid)
    } catch (e) {
      t = false
    }
    return t
  },
  ab: function (e) { },
  util: require("we7/resource/js/util.js"),
  siteInfo: require("siteinfo.js"),
  globalData: {
    appid: 'liu2417301781',
    userInfo: null,
    card_id:0,
    app_name: '小程序',
    show_red:1,
    getphone: false,
    user_source: 1
  },
  //拼团
  redirect: function (url, param) {
    wx.navigateTo({
      url: '/yb_mingpian/pages/pintuan/pages/' + url + '?' + param
    })
  },
  showModal: function (that) {
    var animation = wx.createAnimation({
      duration: 200,
    })
    animation.opacity(0).rotateX(-100).step();
    that.setData({
      // animationData:animation.width('291px'),
      animationData: animation.export()
    })
    setTimeout(function () {
      animation.opacity(1).rotateX(0).step();
      that.setData({
        animationData: animation
      });
    }.bind(that), 200)
  },
  showToast: function (that, title) {
    var toast = {};
    toast.toastTitle = title;
    that.setData({
      toast: toast
    })
    var animation = wx.createAnimation({
      duration: 100
    })
    animation.opacity(0).rotateY(-100).step();
    toast.toastStatus = true;
    toast.toastAnimationData = animation.export()
    that.setData({
      toast: toast
    })
    setTimeout(function () {
      animation.opacity(1).rotateY(0).step();
      toast.toastAnimationData = animation
      that.setData({
        toast: toast
      });
    }.bind(that), 100)
    // 定时器关闭 
    setTimeout(function () {
      toast.toastStatus = false
      that.setData({
        toast: toast
      });
    }.bind(that), 2000);
  }
})